// 建立路由模块
// 添加 express 依赖
const express = require("express");
// 添加路由依赖
const router = express.Router()
// 引入数据库文件
const {db,genid} = require("../db/DbUtils")

// 列表接口
router.get("/list", async (req,res) => {
    
    const search_sql = "SELECT * FROM `category`"
    let { err,rows } = await db.async.all(search_sql,[])

    if(err == null){
        res.send({
            code:200,
            msg:"查询成功",
            rows //rows:rows
        })
    }
    else{
        res.send({
            code:500,
            msg:"查询失败"
        })
    }
})

//删除接口  接口写法形式 /category/delete?id=xxx
router.delete("/_token/delete", async (req,res) => {
    

    let id = req.query.id
    
    console.log("后端接受到的删除消息: " + id);

    const delete_sql = "DELETE FROM `category` WHERE `id` = ?"
    let { err,rows } = await db.async.run(delete_sql,[ id ])

    if(err == null){
        res.send({
            code:200,
            msg:"删除成功"
        })
    }
    else{
        res.send({
            code:500,
            msg:"删除失败"
        })
    }
})

// 修改接口
router.put("/_token/update", async (req,res) => {
    
//#region 

    // let { token } = req.headers;
    
    // let admin_token_sql = "SELECT * FROM 'admin' WHERE token = ?"
    // let adminResult = await db.async.all(admin_token_sql,[token])

    // if(adminResult.err != null || adminResult.rows.length == 0){
    //     res.send({
    //         code:403, 
    //         msg: "请先登录"
    //     })
    //     return
    // }

    //#endregion



    let{id,name} = req.body

    console.log("后端接收到的消息: " + id,name);
 
    const update_sql = "UPDATE `category` SET `name` = ? WHERE `id` = ? "
    let { err,rows } = await db.async.run(update_sql,[ name,id ])
  
    if(err == null){
        res.send({
            code:200,
            msg:"修改成功"
        })
    }
    else{
        res.send({
            code:500,
            msg:"修改失败"
        })
    }
})


// 添加接口
router.post("/_token/add", async (req,res) => {
    
    let{name} = req.body
    const insert_sql = "INSERT INTO `category` (`id`,`name`) VALUES (?,?)"
    let { err,rows } = await db.async.run(insert_sql,[genid.NextId(),name])

    if(err == null){
        res.send({
            code:200,
            msg:"添加成功"
        })
    }
    else{
        res.send({
            code:500,
            msg:"添加失败"
        })
    }
})

// 将路由对象导出
module.exports = router